package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.InOutRecordAdapter;
import com.jsnj33.pdaproject.adapter.RecordAdapter;
import com.jsnj33.pdaproject.bean.InOutBean;
import com.jsnj33.pdaproject.bean.InOutRecordBean;
import com.jsnj33.pdaproject.bean.RecordBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.TimeUtils;
import com.jsnj33.pdaproject.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;

import static com.jsnj33.pdaproject.utils.TimeUtils.FORMAT_YM2;

/**
 * @Method： RecordActivity
 * @Author: 萤火虫
 * @Email:allensuns@163.com
 * @Description 进库出库记录查询
 */
public class InOutRecordActivity extends AppCompatActivity {
    private static final String TAG = "RecordActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    ImageView iv_back;
    TextView tvTitle;
    RecyclerView mRecyclerView;
    SmartRefreshLayout SmartRefreshLayout;
    InOutRecordAdapter mRecordAdapter;

    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;

    private boolean isScaning = false;
    int page = 1;
    String user = "";
    String oper_flag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_inout);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        oper_flag = getIntent().getStringExtra("oper_flag");
        initView();
        Listener();
    }

    private void initView() {
        iv_back = findViewById(R.id.iv_back);
        tvTitle = findViewById(R.id.title);
        String title = getIntent().getStringExtra("title");
        tvTitle.setText(title);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        mRecordAdapter = new InOutRecordAdapter(null);
        mRecyclerView.setAdapter(mRecordAdapter);
    }


    private void Listener() {

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }


    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();
        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);
    }

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            Log.i(TAG, "onReceive: " + temp);
            String str = new String(barcode, 0, barcodelen);

            Log.i(TAG, "onReceive: " + str);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(InOutRecordActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);

            Pattern p = Pattern.compile("[a-zA-z]");
            if (sbs.equals("TZ")) {
                ToastUtil.showLongToast(InOutRecordActivity.this, "请扫描工号");
                return;
            } else if (!p.matcher(str).find()) {
                ToastUtil.showLongToast(InOutRecordActivity.this, "请扫描工号");
                return;
            } else {
                /**
                 * 工号
                 */
                user = str;
                quearRecord(user);
                return;
            }
        }

    };

    /**
     * 查询出库入库记录
     *
     * @param barcode
     */
    private void quearRecord(final String barcode) {

        boolean b = judgeString(barcode);
        if (b == true) {
            ToastUtil.showGravityToast(InOutRecordActivity.this, "二维码不存在！！！", Gravity.CENTER, 0, 0);
            return;
        }

        String url = Constants.SUBMIT_INOUTRECORD;
        final HashMap map = new HashMap();
        map.put("usr_no", barcode);
        map.put("oper_flag", oper_flag);
        String gson = new Gson().toJson(map);
        RequestParams requestParams = new RequestParams(url);
        requestParams.setBodyContent(gson);
        Log.d(TAG, " url=: " + url);
        Log.d(TAG, " params=: " + gson);
        requestParams.setAsJsonContent(true);
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                String str = new String(result.toString());
                Log.i(TAG, "onSuccess: " + str);
                InOutRecordBean record = new Gson().fromJson(str, InOutRecordBean.class);
                if (record.getRespCode().equals("1")) {
                    mRecordAdapter.setNewData(record.getRespData());
                } else {
                    ToastUtil.showLongToast(InOutRecordActivity.this, record.getRespMsg());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showLongToast(InOutRecordActivity.this, "网络异常");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private boolean judgeString(String... str) {
        for (int i = 0; i < str.length; i++) {
            if (StringUtility.isEmpty(str[i])) {
                return true;
            }
        }
        return false;
    }
}
